package org.database.filter.service.impl;

import org.database.filter.model.TuNhan;
import org.database.filter.repository.TuNhanRepository;
import org.database.filter.service.NhaDauTuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class NhaDauTuServiceImpl implements NhaDauTuService {
	private static final int MAX_ADDRESS_LENGTH = 199;
	private static final int MAX_NAME_LENGTH = 29;
	private static final String DOT = "\\.";
	private static final String GP_CHARACTER = "gp:";
	@Autowired
	private TuNhanRepository nhaDauTuRepository;

	public void saveOrUpdate(TuNhan ndt) {
		if(ndt.getTEN() != null) {
			ndt.setTEN(ndt.getTEN().replace(GP_CHARACTER, ""));
		}
		if(ndt.getTEN() !=null && ndt.getTEN().trim().endsWith(DOT) && ndt.getTEN().length() >=4 ) {
			ndt.setTEN(ndt.getTEN().substring(0, ndt.getTEN().length()-3));
		}
		if (ndt.getTEN() != null && ndt.getTEN().length() > MAX_NAME_LENGTH) {
			ndt.setTEN(ndt.getTEN().substring(0, MAX_NAME_LENGTH));
		}
		if (ndt.getCHO_O_HIEN_NAY() != null
				&& ndt.getCHO_O_HIEN_NAY().length() > MAX_ADDRESS_LENGTH) {
			ndt.setCHO_O_HIEN_NAY(ndt.getCHO_O_HIEN_NAY().substring(0, MAX_ADDRESS_LENGTH));
		}
		if (ndt.getHO_KHAU() != null && ndt.getHO_KHAU().length() > MAX_ADDRESS_LENGTH) {
			ndt.setHO_KHAU(ndt.getHO_KHAU().substring(0, MAX_ADDRESS_LENGTH));
		}
		try{
		if (ndt.getCMND_PASSPORT() != null) {
			if (nhaDauTuRepository.findOne(ndt.getCMND_PASSPORT()) == null) {
				nhaDauTuRepository.save(ndt);
			}
		} else {
			ndt.setCMND_PASSPORT(String.valueOf(nhaDauTuRepository
					.getNumberOfRecord()));
			nhaDauTuRepository.save(ndt);
		}
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
	}
}
